package com.sxm.yiwei.activitis;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sxm.yiwei.MainActivity;
import com.sxm.yiwei.R;
import com.sxm.yiwei.adapters.CollectServiceAdapter;
import com.sxm.yiwei.beans.ColService;
import com.sxm.yiwei.utils.InternetAddressUtis;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

public class MsgCollectActivity extends BaseActivity implements View.OnClickListener{
    private String TAG ="Collect";
    private ImageView collectback;
    private SlideListView1 cservicelist;
    private SharedPreferences sharedPreferences;
    private String token;
    private String userId;
    private String appId;
    private int no = 1;
    private CollectServiceAdapter adapter;
    private ImageView nodata;
    private ImageView backmain;
    private View mFooterView;
    private List<ColService.DataBean> list = new ArrayList<ColService.DataBean>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_msg_collect);
        sharedPreferences = getSharedPreferences("userlogin", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        userId = sharedPreferences.getString("userId", "");
        appId = sharedPreferences.getString("appid", "");
        initCoolectView();
        getCollectServiceListData(no);

       adapter = new CollectServiceAdapter(MsgCollectActivity.this,list);
        cservicelist.setAdapter(adapter);
        cservicelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String id1 = adapter.list.get(position).getId();
                Intent intent = new Intent(MsgCollectActivity.this,FWContentActivity.class);
                intent.putExtra("id",id1);
                startActivity(intent);
            }
        });
        adapter.setOnClickDelete(new CollectServiceAdapter.OnClickDelete() {
            @Override
            public void OnDelete(int p) {
                // 删除数据
                ColService.DataBean dataBean = adapter.list.get(p);

                collectService(dataBean.getId(),p);

            }
        });


        cservicelist.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (firstVisibleItem == 0) {
                    View firstVisibleItemView = cservicelist.getChildAt(0);
                    if (firstVisibleItemView != null && firstVisibleItemView.getTop() == 0) {
                        no++;
                        getCollectServiceListData(no);
                    }
                } else if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
                    View lastVisibleItemView = cservicelist.getChildAt(cservicelist.getChildCount() - 1);
                    if (lastVisibleItemView != null && lastVisibleItemView.getBottom() == cservicelist.getHeight()) {
                        no++;
                        getCollectServiceListData(no);

                    }
                }
            }
        });
    }

    private void getCollectServiceListData(int no) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.CEOLLECTSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("appId", appId);
        params.addHeader("token", token);
        params.addHeader("userId", userId);
        JSONObject obj = new JSONObject();
        obj.put("pageNo",no+"");
        obj.put("pageSize","20");
        params.addParameter("params",obj.toJSONString());
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                JSONObject obj = JSON.parseObject(result);
                String status = obj.getString("status");
                if (status.equals("1")){
                    getUtilData(result);
                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.d(TAG, "onError: 收藏--collect--"+ex);
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    private void getUtilData(String result) {
        JSONObject object = JSON.parseObject(result);
        JSONArray data = object.getJSONArray("data");

        if (data.size()==0){

        }else {
            nodata.setVisibility(View.GONE);
        }
        for (int i = 0; i < data.size(); i++) {
            ColService.DataBean dataBean = new ColService.DataBean();
            JSONObject obj1 = JSON.parseObject(String.valueOf(data.get(i)));
            String id = obj1.getString("id");
            String intro = obj1.getString("intro");
            String name = obj1.getString("name");
            String rewardCount = obj1.getString("rewardCount");
            String serviceAvatar = obj1.getString("serviceAvatar");
            dataBean.setName(name);
            dataBean.setId(id);
            dataBean.setServiceAvatar(serviceAvatar);
            dataBean.setIntro(intro);
            if (rewardCount==null){
                dataBean.setRewardCount(0);
            }else {
                dataBean.setRewardCount(Integer.valueOf(rewardCount));
            }

            list.add(dataBean);

        }
        adapter.notifyDataSetChanged();

    }

    private void initCoolectView() {
        collectback = (ImageView) findViewById(R.id.message_collectback);
        cservicelist = (SlideListView1) findViewById(R.id.colectservice_list);
        nodata = (ImageView) findViewById(R.id.msgcollect_nodata);
        backmain = (ImageView) findViewById(R.id.msgcollect_backmain);
        backmain.setOnClickListener(this);
        collectback.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.message_collectback:
                finish();
                break;
            case R.id.msgcollect_backmain:

                startActivity(new Intent(MsgCollectActivity.this, MainActivity.class));
                AppManager.getAppManager().finishAllActivity();
                break;
        }
    }
    //收藏服务
    private void collectService(String id, final int p) {
        RequestParams params = new RequestParams(InternetAddressUtis.Url+InternetAddressUtis.COLLECTSERVICE);
        params.addHeader("Content-Type","application/json");
        params.addHeader("token",token);
        params.addHeader("appId",appId);
        params.addHeader("userId",userId);

        JSONObject object = new JSONObject();
        object.put("serviceId",id);
        params.setBodyContent(object.toJSONString());
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Toast.makeText(MsgCollectActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
               adapter.list.remove(p);
                adapter.notifyDataSetChanged();
                try {
                    cservicelist.turnToNormal();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                cservicelist.invalidate();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
